define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/order/index' + location.search,
                    // add_url: 'order/order/add',
                    // edit_url: 'order/order/edit',
                    del_url: 'order/order/del',
                    multi_url: 'order/order/multi',
                    import_url: 'order/order/import',
                    table: 'order',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='user_id']", form)
                    .addClass("selectpage")
                    .data("source", "user/user/index")
                    .data("primaryKey", "id")
                    .data("field", "nickname")
                    .data("orderBy", "id desc");
                // $("input[name='shop_id']", form)
                //     .addClass("selectpage")
                //     .data("source", "shop/shop/index")
                //     .data("primaryKey", "id")
                //     .data("field", "shopname")
                //     .data("orderBy", "id desc");
                // $("input[name='claim_shop_id']", form)
                //     .addClass("selectpage")
                //     .data("source", "shop/shop/index")
                //     .data("primaryKey", "id")
                //     .data("field", "shopname")
                //     .data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            //当双击单元格时
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-detail", element).trigger("click");
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID')},
                        {field: 'unique_order_no', title: __('Unique_order_no'), operate: 'LIKE'},
                        {field: 'order_no', title: __('Order_no'), operate: 'LIKE'},
                        // {field: 'user_id', title: __('User_id'), operate: false, formatter: Table.api.formatter.search},
                        {field: 'user_id', title: __('User_id'), visible:false, operate: 'LIKE %...%'},
                        {field: 'user.nickname', title: __('User_id'), operate: false},
                        // {field: 'shop_id', title: __('Shop_id'), visible:false, operate: 'LIKE %...%'},
                        // {field: 'shop.shopname', title: __('Shop_id'), operate: false},
                        // {field: 'claim_shop_id', title: __('Claim_shop_id'), visible:false, operate: 'LIKE %...%'},
                        // {field: 'claimshop.shopname', title: __('Claim_shop_id'), operate: false},
                        // {field: 'goods_price', title: __('Goods_price'), operate:'BETWEEN'},
                        // {field: 'coupon_id', title: __('Coupon_id')},
                        // {field: 'delivery_price', title: __('Delivery_price'), operate:'BETWEEN'},
                        // {field: 'coupon_price', title: __('Coupon_price'), operate:'BETWEEN'},
                        // {field: 'order_price', title: __('Order_price'), operate:'BETWEEN'},
                        {field: 'total_fee', title: __('Total_fee'), operate:'BETWEEN'},
                        // {field: 'last_total_fee', title: __('Last_total_fee'), operate:'BETWEEN'},
                        {field: 'pay_price', title: __('Pay_price'), operate:'BETWEEN'},
                        // {field: 'is_pay', title: __('Is_pay'), searchList: {"0":__('Is_pay 0'),"1":__('Is_pay 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'pay_type', title: __('Pay_type'), searchList: {"alipay":__('Pay_type alipay'),"wxpay":__('Pay_type wxpay'),"wallet":__('Pay_type wallet'),"public":__('Pay_type public'),"private":__('Pay_type private')}, formatter: Table.api.formatter.normal},
                        {field: 'pay_type', title: __('Pay_type'), searchList: {"alipay":__('Pay_type alipay'),"wxpay":__('Pay_type wxpay'),"wallet":__('Pay_type wallet')}, formatter: Table.api.formatter.normal},
                        // {field: 'pay_order_no', title: __('Pay_order_no'), operate: 'LIKE'},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3'),"4":__('Status 4'),"5":__('Status 5')}, formatter: Table.api.formatter.status},
                        // {field: 'order_settlement_type', title: __('Order_settlement_type'), searchList: {"cash":__('Order_settlement_type cash'),"credit":__('Order_settlement_type credit')}, formatter: Table.api.formatter.normal},
                        // {field: 'is_settlement', title: __('Is_settlement'), searchList: {"0":__('Is_settlement 0'),"1":__('Is_settlement 1')}, formatter: Table.api.formatter.normal},
                        {field: 'is_close', title: __('Is_close'), searchList: {"0":__('Is_close 0'),"1":__('Is_close 1')}, formatter: Table.api.formatter.normal},
                        {field: 'is_burst_order', title: __('Is_burst_order'), searchList: {"0":__('Is_burst_order 0'),"1":__('Is_burst_order 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'contact', title: __('Contact'), operate: 'LIKE'},
                        // {field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
                        // {field: 'province', title: __('Province'), operate: 'LIKE'},
                        // {field: 'city', title: __('City'), operate: 'LIKE'},
                        // {field: 'area', title: __('Area'), operate: 'LIKE'},
                        // {field: 'address', title: __('Address'), operate: 'LIKE'},
                        {field: 'express', title: __('收货信息'), operate: false, formatter: function (value,row,index) {
                                return row.contact +"/"+ row.mobile +"<br>"+ row.province + row.city + row.area  +"<br>"+ row.address;
                            }},
                        // {field: 'remark', title: __('Remark'), operate: 'LIKE'},
                        // {field: 'trade_no', title: __('Trade_no'), operate: 'LIKE'},
                        // {field: 'goods_num', title: __('Goods_num')},
                        // {field: 'is_sales', title: __('Is_sales'), searchList: {"0":__('Is_sales 0'),"1":__('Is_sales 1'),"2":__('Is_sales 2')}, formatter: Table.api.formatter.normal},
                        // {field: 'platform', title: __('Platform'), searchList: {"mini":__('Platform mini'),"pc":__('Platform pc'),"app":__('Platform app')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'pay_time', title: __('Pay_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'received_time', title: __('Received_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'close_time', title: __('Close_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons:[
                                {
                                    name: 'detail',
                                    text: '订单详情',
                                    title: '订单详情',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-sticky-note-o',
                                    extend: 'data-area=\'["90%", "90%"]\'',
                                    url: function (res) {
                                        return 'order/order/detail/ids/' + res.id;
                                    },
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        return true;
                                    }
                                }
                            ], formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            var options = table.bootstrapTable('getOptions');
            var queryParams = options.queryParams;
            // 绑定TAB事件
            $('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var value = $(this).data("value");
                options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    if (value) {
                        params.filter = JSON.stringify(value);
                        let op = {}
                        for (let i in value) {
                            op[i] = '=';
                        }
                        params.op = JSON.stringify(op);
                    }
                    params = queryParams.call(this, params);
                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'order/order/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'order/order/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'order/order/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        settlement: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            // Controller.api.bindevent();
            $(document).on("click", ".btn-refresh", function () {
                setTimeout(function () {
                    location.reload();
                }, 1000);
            });
            //取消，支付
            $(document).on('click', '.btn-status-click', function () {
                let order = $(this).data('order');
                let order_id = $('#order_id').val();
                $.post('order/order/edit_status', {
                    order_id,
                    ...order
                }, function (res) {
                    if (res.code == 1) {
                        window.location.reload();
                        parent.Toastr.success(res.msg);
                    } else {
                        parent.Toastr.error(res.msg);
                    }
                })
            });

            //发货
            $(document).on('click', '.btn-deliver', function () {
                let expressname = $(this).data('expressname');
                let expressno = $(this).data('expressno');
                let html = Template('expresstpl', {expressname, expressno});
                let type = $(this).data('type');
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    title: type == 0 ? '发货' : '修改快递信息',
                    anim: 2,
                    area: ['400px', '300px'],
                    shadeClose: 1, //开启遮罩关闭
                    content: html,
                    btn: ['确认', '取消'],
                    zIndex: 10,
                    yes: function (index) {
                        // let FactoryId = ($('#FactoryId').val()).trim();
                        let express_name = ($('#express_name').val()).trim();
                        let express_no = ($('#express_no').val()).trim();
                        if (!express_name) {
                            Toastr.error('请输入快递名称');
                            return;
                        }
                        if (!express_no) {
                            Toastr.error('请输入快递单号');
                            return;
                        }
                        let order_id = $('#order_id').val();
                        $.post('order/order/send', {
                            order_id,
                            // FactoryId,
                            express_name,
                            express_no,
                            type
                        }, function (res) {
                            if (res.code == 1) {
                                window.location.reload();
                                Toastr.success(res.msg);
                                Layer.close(index);
                            } else {
                                Toastr.error(res.msg);
                            }
                        })

                    },
                    success: function (layero, index) {
                        Form.api.bindevent($('.shipper'));
                    }
                });
            });

            //重新下推
            $(document).on('click', '.btn-push-order', function () {
                let order_no = $(this).data('order_no');
                $.post("{:url('api/Heng9/NewNetOrder')}", {
                    order_no,
                }, function (res) {
                    if (res.code == 200) {
                        window.location.reload();
                        Toastr.success(res.msg);
                        Layer.close(index);
                    } else {
                        Toastr.error(res.msg);
                    }
                })
            });

            //编辑备注
            $('#app').delegate('.btn-edit,.btn-cancel,.btn-save', 'click', function () {
                let status = $(this).data('status');
                switch (status) {
                    case 'edit':
                        $(this).nextAll('a').removeClass('hide');
                        $(this).parent().prev().children('div').addClass('hide');
                        $(this).parent().prev().children('input').removeClass('hide');
                        $(this).addClass('hide');
                        break;
                    case 'cancel':
                        $(this).prev().removeClass('hide');
                        $(this).next().addClass('hide');
                        $(this).parent().prev().children('div').removeClass('hide');
                        $(this).parent().prev().children('input').addClass('hide');
                        $(this).addClass('hide');
                        break;
                    case 'save':
                        let val = $(this).parent().prev().children('input').val();
                        let field = $(this).data('field');
                        let id = $(this).data('id');
                        $.post('order/order/edit_info', {
                            id: id,
                            field: field,
                            value: val
                        }, function (res) {
                            if (res.code == 1) {
                                window.location.reload();
                                parent.Toastr.success(res.msg);
                            } else {
                                parent.Toastr.error(res.msg);
                            }
                        })
                        break;
                }
            });


            function moneyPrompt(value) {
                return new Promise((resolve, reject) => {
                    layer.prompt({
                        title: '确认退款金额',
                        formType: 0,
                        value: value
                    }, function (pass, index) {
                        layer.close(index);
                        resolve(pass)
                    });
                })
            }

            function reasonPrompt() {
                return new Promise((resolve, reject) => {
                    layer.prompt({
                        title: '拒绝原因',
                        formType: 2
                    }, function (pass, index) {
                        layer.close(index);
                        resolve(pass)
                    });
                })
            }

            Form.api.bindevent($('.electronics'));

            //查询物流
            $(document).on('click', '.btn-logistics', function () {
                var expressno = $(this).data('expressno');
                var wuliu = expressno.substr(0,2);
                parent.layer.open({
                    type: 2,
                    shade: false,
                    zIndex: 9999999999,
                    title: '物流信息',
                    area: ['90%', '90%'],
                    content: 'https://www.kuaidi100.com/all/'+wuliu+'.shtml?mscomnu=' + $(this).data('expressno')
                })
            })
        },
        // send: function () {
        //     Controller.api.bindevent();
        // },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
